package chapter03;

import java.util.Arrays;

public class QuickSort {
    public static void main(String[] args) {
        int[] arr = {6, 1, 8, 2, 3, 7, 5, 9, 4, 12};
//        int[] arr = {13, 6, 8, 2, 3, 7, 5, 9, 4, 12};
//        int[] arr = {1, 6, 8, 2, 3, 7, 5, 9, 4, 12};

        quickSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    public static void quickSort(int[] arr, int L, int R) {
        if (L >= R || L < 0 || R >= arr.length) {
            return;
        }
        int first = arr[L];
        int left = L + 1;
        int right = R;

        while (left <= right) {
            if (arr[left] <= first) {
                left++;
            } else {
                swap(arr, left, right--);
            }
        }
        swap(arr, L, right);
        quickSort(arr, L, right - 1);
        quickSort(arr, right + 1, R);
    }

    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
